<template>
  <div class="cropper-content">
    <div class="cropper-box">
      <div class="cropper">
        <vue-cropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :fixed="fixed"
          :fixed-number="fixedNumber"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :fixed-box="option.fixedBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :center-box="option.centerBox"
          @img-load="imgLoad"
          @real-time="realTime"
        >
        </vue-cropper>
      </div>
      <!--底部操作工具按钮-->
      <div class="footer-btn">
        <div class="scope-btn">
          <label class="btn" for="uploads">选择图片</label>
          <input
            type="file"
            id="uploads"
            style="position: absolute; clip: rect(0 0 0 0)"
            accept="image/png, image/jpeg, image/gif, image/jpg"
            @change="selectImg"
          />
          <el-button size="mini" type="danger" plain @click="changeScale(1)">+ 放大</el-button>
          <el-button size="mini" type="danger" plain @click="changeScale(-1)">- 缩小</el-button>
          <el-button size="mini" type="danger" plain @click="rotateLeft">↺ 左旋转</el-button>
          <el-button size="mini" type="danger" plain @click="rotateRight">↻ 右旋转</el-button>
          <el-button size="mini" type="success" @click="finish" :disabled="disable"
            >完成
          </el-button>
        </div>
      </div>
    </div>
    <!--预览效果图-->
    <div
      class="show-preview"
      :style="{
        width: previews.w + 'px',
        height: previews.h + 'px',
        overflow: 'hidden',
        margin: '.3125rem'
      }"
    >
      <div class="preview" :style="previews.div">
        <img :src="previews.url" :style="previews.img" />
      </div>
    </div>
  </div>
</template>

<script setup>
import 'vue-cropper/dist/index.css'
import { ref, defineEmits, reactive } from 'vue'
import { VueCropper } from 'vue-cropper'
import useUserStore from '@/store/user/user.ts'

//用store保存截取后的图片信息
const userStore = useUserStore()
//注册触发的事件
const emit = defineEmits(['finish'])

//实时裁剪效果的数据
const previews = ref({})
//用于获取cropper里面的方法
const cropper = ref({})
//完成按钮是否可用，如果用户未上传图片则不可用
const disable = ref(true)
//配置
const option = ref({
  img: '', //裁剪图片的地址
  size: 1,
  outputSize: 1, //裁剪生成图片的质量(可选0.1 - 1)
  outputType: 'jpeg', //裁剪生成图片的格式（jpeg || png || webp）
  info: true, //图片大小信息
  canScale: true, //图片是否允许滚轮缩放
  autoCrop: true, //是否默认生成截图框
  autoCropWidth: 150, //默认生成截图框宽度
  autoCropHeight: 150, //默认生成截图框高度
  fixed: true, //是否开启截图框宽高固定比例
  fixedNumber: [1, 1], //截图框的宽高比例
  full: false, //false按原比例裁切图片，不失真
  fixedBox: true, //固定截图框大小，不允许改变
  canMove: true, //上传图片是否可以移动
  canMoveBox: true, //截图框能否拖动
  original: false, //上传图片按照原始比例渲染
  centerBox: true, //截图框是否被限制在图片里面
  height: true, //是否按照设备的dpr 输出等比例图片
  infoTrue: false, //true为展示真实输出图片宽高，false展示看到的截图框宽高
  maxImgSize: 3000, //限制图片最大宽度和高度
  enlarge: 1, //图片根据截图框输出比例倍数
  mode: 'cover' //图片默认渲染方式
})
const imgLoad = (msg) => {
  console.log('工具初始化函数=====' + msg)
  //如果工具能初始化，说明有图片
  disable.value = false
}
//图片缩放
const changeScale = (num) => {
  num = num || 1
  cropper.value.changeScale(num)
}
//向左旋转
const rotateLeft = () => {
  cropper.value.rotateLeft()
}
//向右旋转
const rotateRight = () => {
  cropper.value.rotateRight()
}
//实时预览函数
const realTime = (data) => {
  previews.value = data
}
//选择图片
const selectImg = (e) => {
  const file = e.target.files[0]

  if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
    return false
  }
  const reader = new FileReader()
  reader.onload = (e) => {
    option.value.img = e.target.result
    const beginIndex = e.target.result.indexOf('/')
    const endIndex = e.target.result.indexOf(';')
    const filetype = e.target.result.substring(beginIndex + 1, endIndex)
    option.value.outputType = filetype
  }
  //异步的读取，当读取完触发onload事件
  reader.readAsDataURL(file)
}
//裁剪完成
const finish = () => {
  userStore.bustTemp = previews.value
  cropper.value.getCropData((data) => {
    userStore.bustTemp = data
    userStore.fileType = option.value.outputType
    const ruleForm = reactive({
      userId: userStore.userMessage.userId,
      userBust: userStore.userMessage.userBust,
      userVita: userStore.userMessage.userVita,
      nickname: userStore.userMessage.nickname,
      username: userStore.userMessage.username,
      password: userStore.userMessage.password,
      userEmail: userStore.userMessage.userEmail,
      phoneNumber: userStore.userMessage.phoneNumber,
      skill: userStore.userMessage.skill,
      score: userStore.userMessage.score,
      age: userStore.userMessage.age,
      sex: userStore.userMessage.sex
    })
    userStore.updateUserInformation(ruleForm)
  })
  emit('finish')
}
</script>

<style scoped lang="less">
.cropper-content {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  .cropper-box {
    flex: 1;
    width: 100%;
    .cropper {
      width: auto;
      height: 300px;
    }
  }

  .show-preview {
    flex: 1;
    display: flex;
    justify-content: center;
    .preview {
      overflow: hidden;
      border: 1px solid #ccc;
      border-radius: 50%;
    }
  }
}
.footer-btn {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  .scope-btn {
    display: flex;
    justify-content: space-between;
    padding-right: 10px;
  }
  .upload-btn {
    flex: 1;
    display: flex;
    justify-content: center;
  }
  .btn {
    outline: none;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    text-align: center;
    box-sizing: border-box;
    outline: 0;
    -webkit-transition: 0.1s;
    transition: 0.1s;
    font-weight: 500;
    padding: 8px 15px;
    font-size: 12px;
    border-radius: 3px;
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    margin-right: 10px;
  }
}
</style>
